package edu.worldskills.b;

import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageDecoder;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class MyActivity extends AppCompatActivity {

    private static final String TAG = "MyActivity";
    private ImageView imageView;
    private ActivityResultLauncher<String[]> getContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        //加载图片
        loadPics();

        Button btn_upLoad = findViewById(R.id.btn_upload);
        btn_upLoad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showImageUploadDialog();
            }
        });


        Button btn_home = findViewById(R.id.btn_home);
        btn_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MyActivity.this, HomeActivity.class);
                startActivity(intent);
            }
        });


        //必须要在onCreate()先注册相册回调方法
        //将选择的照片在对话框中的ImageView显示
        getContent = registerForActivityResult(new ActivityResultContracts.OpenDocument(),
                new ActivityResultCallback<Uri>() {
                    @Override
                    public void onActivityResult(Uri uri) {
                        if (uri != null) {
                            try {
                                // 使用InputStream和BitmapFactory加载图片
                                InputStream inputStream = getContentResolver().openInputStream(uri);
                                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                                imageView.setImageBitmap(bitmap);

                                if (inputStream != null) {
                                    inputStream.close(); // 记得关闭InputStream
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }
                });
    }


    //显示上传图片对话框
    private void showImageUploadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_image_upload, null);
        builder.setView(dialogView);

        EditText etImageTitle = dialogView.findViewById(R.id.etImageTitle);
        EditText etImageDescription = dialogView.findViewById(R.id.etImageDescription);
        imageView = dialogView.findViewById(R.id.selectImageView);

        Button btnSelectImage = dialogView.findViewById(R.id.btnSelectImage);
        Button btnCancel = dialogView.findViewById(R.id.btnCancel);
        Button btnUpload = dialogView.findViewById(R.id.btnUpload);

        AlertDialog dialog = builder.create();
        dialog.show();

        //选择照片
        btnSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getContent.launch(new String[]{"image/*"});
            }
        });


        //取消
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
//
        //上传,保存到相册
        btnUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                String title = etImageTitle.getText().toString();
//                String description = etImageDescription.getText().toString();
                Drawable drawable = imageView.getDrawable();
                Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
                Function.saveBitmapToPictures(bitmap,MyActivity.this);
                loadPics();
                dialog.dismiss();
            }
        });
    }

    private void loadPics() {

        GridLayout layout = findViewById(R.id.my_container);
        layout.removeAllViews();

        //获取Pictures中所有图片
        List<String> imagePaths = getPicturesFromMediaStore();
        for (String imagePath : imagePaths) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);

            //创建cardview
            CardView cardView = new CardView(MyActivity.this);
            cardView.setRadius(30);
            cardView.setElevation(50);
            GridLayout.LayoutParams g_params = new GridLayout.LayoutParams();
            g_params.width = 450;
            g_params.height = GridLayout.LayoutParams.WRAP_CONTENT;
            g_params.setMargins(60, 80, 0, 0);
            cardView.setLayoutParams(g_params);

            //创建imageview
            ImageView imageView = new ImageView(getApplicationContext());
            imageView.setImageBitmap(bitmap);
            LinearLayout.LayoutParams l_params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT
            );
            imageView.setAdjustViewBounds(true);
            imageView.setLayoutParams(l_params);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

            cardView.addView(imageView);
            layout.addView(cardView);
        }
    }


    // 获取 Pictures 文件夹中的所有图片
    private List<String> getPicturesFromMediaStore() {
        List<String> images = new ArrayList<>();
        Uri collection = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

        // 查询条件：只获取 Pictures 文件夹下的图片
        String selection = MediaStore.Images.Media.RELATIVE_PATH + " LIKE ?";
        String[] selectionArgs = new String[]{"%Pictures%"};

        String[] projection = {MediaStore.Images.Media.DATA}; // 获取图片的文件路径

        Cursor cursor = getContentResolver().query(
                collection,
                projection,
                selection,
                selectionArgs,
                null
        );

        if (cursor != null) {
            int dataColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            while (cursor.moveToNext()) {
                String imagePath = cursor.getString(dataColumnIndex);
                images.add(imagePath); // 添加图片路径到列表
            }
            cursor.close();
        }
        return images;
    }


//    public void saveBitmapToPictures(Bitmap bitmap) {
//        // 获取 Pictures 文件夹路径
//        String fileName = UUID.randomUUID().toString();
//
//        // 获取Pictures路径
//        File picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
//
//        // 创建目标文件
//        File file = new File(picturesDir, fileName + ".png");
//        FileOutputStream outputStream = null;
//
//        try {
//            outputStream = new FileOutputStream(file);
//
//            // 将 Bitmap 写入文件，压缩格式为 PNG，质量为 100（最高质量）
//            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
//            Toast.makeText(getApplicationContext(), "图片保存成功：" + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
//
//        } catch (IOException e) {
//            e.printStackTrace();
//            Toast.makeText(getApplicationContext(), "保存失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
//        } finally {
//            if (outputStream != null) {
//                try {
//                    outputStream.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//
//    }
}